//
//  StoneShowViewController.m
//  Globalstone
//
//  Created by 刘建峰 on 16/7/9.
//  Copyright © 2016年 yuf. All rights reserved.
//

#import "StoneShowViewController.h"
#import "StoneShowTableViewCell.h"
#import "StoneShowDetailViewController.h"

static NSString * cellIndentifier = @"StoneShowTableViewCell";
@interface StoneShowViewController ()<UITableViewDataSource,UITableViewDelegate,UITextFieldDelegate>{
    NSInteger _totle;
}
@property (nonatomic,assign)   NSInteger    pageNO;

@property (weak, nonatomic) IBOutlet UIView *navView;
@property (weak, nonatomic) IBOutlet UITextField *searchField;
@property (weak, nonatomic) IBOutlet UITableView *leftTableView;
@property (weak, nonatomic) IBOutlet UITableView *rightTableView;
@property(nonatomic,assign)NSInteger leftRow;
@property(nonatomic,assign)NSInteger rightRow;
@property (weak, nonatomic) IBOutlet UILabel *headTitle;
@property (weak, nonatomic) IBOutlet UILabel *backLine;

@property(nonatomic,strong)NSArray * stoneTypes;
@property(nonatomic,strong)NSString * typeId;
@property(nonatomic,strong)NSMutableArray * stonesArray;


@end

@implementation StoneShowViewController

- (void)viewWillAppear:(BOOL)animated{
    [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleLightContent];
  
}

- (void)viewDidLoad {
  
    [super viewDidLoad];
    _leftRow = 0;
    _pageNO = 1;
    _stoneTypes = [NSArray array];
    _stonesArray = [NSMutableArray array];
    [self initViewLayout];
    [self getStoneTypes];
    
    // Do any additional setup after loading the view.
}

- (void)initViewLayout{
    [self adaptiveViewLayout:self.view];
    [self adaptiveViewLayout:self.navView];
    _backLine.layer.borderColor = [UIColor colorWithWhite:0.875 alpha:1.000].CGColor;
    _backLine.layer.borderWidth = 1;
    _backLine.layer.cornerRadius = 4*VerticalRatio();
    _searchField.leftViewMode =  UITextFieldViewModeAlways;
    _searchField.leftView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 8, 1)];
    
    [_rightTableView registerNib:[UINib nibWithNibName:cellIndentifier bundle:nil] forCellReuseIdentifier:cellIndentifier];
    _rightTableView.dataSource = self;
    _rightTableView.delegate = self;
    
    _leftTableView.dataSource = self;
    _leftTableView.delegate = self;
    
    _searchField.delegate = self;
    
}

- (IBAction)back:(id)sender {
     
    [self backBtn];
    
}

#pragma mark == 语言切换
- (void)changeLanguage{
    _headTitle.text = InternationalControl(@"天天石材展");
}


#pragma mark == 石材分类
- (void)getStoneTypes{
    NSMutableDictionary  *dic=[NSMutableDictionary dictionary];

    NSString * lan = [InternationalControl userLanguage];
    if ([lan isEqualToString:@"en"]) {
        [dic setObject:@"2" forKey:@"language"];
    }else{
        [dic setObject:@"1" forKey:@"language"];
    }
    
    self.shareApi.delegate=self;
    [self.shareApi  requestOperationWithDic:dic withPath:GS_queryStoreForeignType withHttpType:@"POST" withTag:GS_GS_queryStoreForeignType];
}


#pragma mark -- 添加刷新数据
- (void)addRefreshing{
    self.rightTableView.header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        int64_t delayInSeconds = 8.0;
        dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, delayInSeconds * NSEC_PER_SEC);
        dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
            [self.rightTableView.header endRefreshing];
        });
        self.pageNO = 1;
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            //请求订单数据
            [self getStoneList];
        });
    }];
    [_rightTableView.header beginRefreshing];
}
//加载更多数据
- (void)loadMoreData{
    if (self.stonesArray.count == _totle) {
        [self.rightTableView.footer endRefreshing];
    }else{
        self.pageNO = self.pageNO + 1;
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            //请求订单数据
            [self getStoneList];
        });
    }
    
}

#pragma mark == 石材列表
- (void)getStoneList{
    NSMutableDictionary  *dic=[NSMutableDictionary dictionary];
    
    NSString * lan = [InternationalControl userLanguage];
    if ([lan isEqualToString:@"en"]) {
        [dic setObject:@"2" forKey:@"language"];
    }else{
        [dic setObject:@"1" forKey:@"language"];
    }
    [dic setObject:_typeId forKey:@"msfoTypeId"];
    [dic setObject:_searchField.text forKey:@"msfoName"];
    self.shareApi.delegate=self;
    [self.shareApi  requestOperationWithDic:dic withPath:GS_queryStoreForeign withHttpType:@"POST" withTag:GS_GS_queryStoreForeign];

}


#pragma mark == 搜索
- (IBAction)searchHandel:(id)sender {
    [self hideKeyBoard];
    [_rightTableView.header beginRefreshing];
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField{
    [self hideKeyBoard];
    [self.rightTableView.header beginRefreshing];
    return YES;
}

#pragma mark  ==== tableViewDelegate

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (tableView == _leftTableView) {
        return _stoneTypes.count;
    }else{
        return _stonesArray.count;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (tableView == _leftTableView) {
        return 43*VerticalRatio();
    }else{
        return 88*VerticalRatio();
    }
    
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (tableView == _leftTableView) {
        UITableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
        if (!cell) {
            cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cell"];
        }
        
        UILabel * bottomLine = [[UILabel alloc]initWithFrame:flexibleFrame(CGRectMake(0, 42, 64, 1), NO)];
        bottomLine.backgroundColor = [UIColor colorWithWhite:0.886 alpha:1.000];
        [cell addSubview:bottomLine];
        
        UILabel * rightLine = [[UILabel alloc]initWithFrame:flexibleFrame(CGRectMake(63,0, 1, 43), NO)];
        rightLine.backgroundColor = [UIColor colorWithWhite:0.886 alpha:1.000];
        [cell addSubview:rightLine];

        
        cell.backgroundColor = [UIColor colorWithWhite:0.957 alpha:1.000];
        if (indexPath.row == _leftRow) {
            cell.backgroundColor = [UIColor whiteColor];
            rightLine.hidden = YES;
        }else{
            rightLine.hidden = NO;
        }
        
        NSDictionary * dic = _stoneTypes[indexPath.row];
        UILabel * label = [[UILabel alloc]initWithFrame:flexibleFrame(CGRectMake(13, 0, 51, 43), NO)];
        label.textColor = [UIColor colorWithRed:0.255 green:0.255 blue:0.020 alpha:1.000];
        label.font = [UIFont systemFontOfSize:15*VerticalTexeRatio()];
        label.text = [NSString stringWithFormat:@"%@",dic[@"mstyName"]];
        [cell addSubview:label];
        
        
        return cell;
    }else{
        StoneShowTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:cellIndentifier];
        if (cell == nil) {
            cell = [[StoneShowTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIndentifier];
        }
        NSDictionary * dic= _stonesArray[indexPath.row];
        cell.stoneName.text = [NSString stringWithFormat:@"%@",dic[@"msfoName"]];
        cell.stoneDetail.text = [NSString stringWithFormat:@"%@",dic[@"msfoDescription"]];
        cell.stoneType.text = [NSString stringWithFormat:@"%@",dic[@"msfoProduct"]];
        
        NSString * image = [NSString stringWithFormat:@"%@",dic[@"mstoImage"]];
        if (image.length>0) {
            [cell.stoneImage sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@%@",IP_Address_ImageDown_Fresh,image]]];
        }
        return cell;
    }
    return nil;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if (tableView==_leftTableView) {
        _leftRow = indexPath.row;
        [_leftTableView reloadData];
        _typeId = [NSString stringWithFormat:@"%@",_stoneTypes[indexPath.row][@"mstyId"]];
        [_stonesArray removeAllObjects];
        [_rightTableView.header beginRefreshing];
    }else{
        UIStoryboard * storyBoard = [UIStoryboard storyboardWithName:@"HomeStoryboard" bundle:nil];
        StoneShowDetailViewController * page = [storyBoard instantiateViewControllerWithIdentifier:@"StoneShowDetail"];
        page.stoneId = _stonesArray[indexPath.row][@"msfoId"];
        [[Common getNavigation]pushViewController:page];

    }
}

#pragma   mark---- GetADBanner Request Delegate

-(void)fetchDatabaseFinished:(NSMutableDictionary *)database withTag:(NSInteger)tag{
    [_rightTableView.header endRefreshing];
    [_rightTableView.footer endRefreshing];
    if (tag == GS_GS_queryStoreForeignType) {
        if (  [[database valueForKey:@"flag"] integerValue]!=1 ) {
            
            [[CWHUDTips sharedInstance]  showTips:[database valueForKey:@"msg"]  withStatus:1 dismissAfter:1.5];
            
        }else  {
            _stoneTypes = database[@"result"];
            [_leftTableView reloadData];
            
            if (_stoneTypes.count>0) {
                _typeId = [NSString stringWithFormat:@"%@",_stoneTypes[0][@"mstyId"]];
                [self addRefreshing];
                [self.rightTableView.header beginRefreshing];
            }
        }
    }else if (tag == GS_GS_queryStoreForeign){
        if (  [[database valueForKey:@"flag"] integerValue]!=1 ) {
            
            [[CWHUDTips sharedInstance]  showTips:[database valueForKey:@"msg"]  withStatus:1 dismissAfter:1.5];
            
        }else  {
            dispatch_async(dispatch_get_main_queue(), ^{
                _totle = [database[@"result"][@"total"] integerValue];
                if (_totle > PageSize) {
                    __weak __typeof(self) weakSelf = self;
                    if (!self.rightTableView.footer) {
                        // 设置回调（一旦进入刷新状态就会调用这个refreshingBlock）
                        self.rightTableView.footer = [MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
                            [weakSelf loadMoreData];
                        }];
                    }
                }
                if (self.pageNO == 1) {
                    [self.stonesArray removeAllObjects];
                }
                NSArray *arr = database[@"result"][@"rows"];
                for (id entity in arr) {
                    [self.stonesArray addObject:entity];
                }
                
                [_rightTableView reloadData];
                
            });

            
        }

    }

    
}
-(void)fetchDatabaseFailed:(NSError *)error message:(NSString *)message{
    [_rightTableView.header endRefreshing];
    [_rightTableView.footer endRefreshing];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
